package ace.module.captcha.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.core.utils.SystemClockUtils;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.AbstractSpringDtoManager;
import ace.cmp.id.generator.api.LongIdGenerator;
import ace.module.captcha.api.model.dto.CaptchaItemConfigDto;
import ace.module.captcha.core.impl.dao.entity.CaptchaItemConfig;
import ace.module.captcha.core.impl.dao.repository.CaptchaItemConfigRepository;
import ace.module.captcha.core.impl.manager.CaptchaItemConfigManager;
import ace.module.captcha.core.impl.properties.CaptchaCoreProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 验证码配置 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class CaptchaItemConfigManagerImpl
    extends AbstractSpringDtoManager<CaptchaItemConfig, Long, CaptchaItemConfigDto>
    implements CaptchaItemConfigManager {

  private final CaptchaCoreProperties properties;
  private final CaptchaItemConfigRepository captchaItemConfigProperties;
  private final LongIdGenerator idGenerator;

  @Override
  public CaptchaItemConfig getSystemDefaultOrCreateByCaptchaAppId(Long captchaAppId) {
    CaptchaItemConfig captchaItemConfig = captchaItemConfigProperties.getById(captchaAppId);
    if (captchaItemConfig != null) {
      return captchaItemConfig;
    }
    captchaItemConfig = this.createDefaultByCaptchaAppId(captchaAppId);
    return captchaItemConfig;
  }

  @Override
  public CaptchaItemConfig createDefaultByCaptchaAppId(Long captchaAppId) {
    CaptchaCoreProperties.CaptchaItemConfigProperties captchaItemConfigProperties =
        properties.getDefaultCaptchaItemConfig();
    CaptchaItemConfig captchaItemConfig =
        CaptchaItemConfig.builder()
            .id(captchaAppId)
            .enable(captchaItemConfigProperties.getEnable())
            .systemCode(captchaItemConfigProperties.getSystemCaptcha())
            .enableSystemCode(captchaItemConfigProperties.getEnableSystemCaptcha())
            .expireInSeconds(captchaItemConfigProperties.getExpireInSeconds())
            .attemptCount(captchaItemConfigProperties.getAttemptCount())
            .updateTime(SystemClockUtils.currentTimeMillis())
            .createTime(SystemClockUtils.currentTimeMillis())
            .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
            .rowVersion(null)
            .build();
    this.captchaItemConfigProperties.insert(captchaItemConfig);
    return captchaItemConfig;
  }
}
